package cn.it.facultystaff.service.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import cn.it.facultystaff.service.UploadFileServer;

public class UploadFileServerImpl implements UploadFileServer {

	public Map<String, String> uploadFile(HttpServletRequest request,String savePath) {
		Map<String,String> params = new HashMap<String,String>();
		
		try {
			if (ServletFileUpload.isMultipartContent(request)) {
				DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

				ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
				
				List<FileItem> items = servletFileUpload.parseRequest(request);
				
				Iterator<FileItem> iter = items.iterator();
				
				InputStream in = null;
				BufferedOutputStream out = null;
				String image_extension=null;
				String photoFieldName=null;
				
				while (iter.hasNext()) {

					FileItem fileItem = iter.next();
					
					if (!fileItem.isFormField() && fileItem.getName().length() > 0) {

						photoFieldName=fileItem.getFieldName();
						
						String filename=fileItem.getName().substring(fileItem.getName().lastIndexOf("\\")+1);
						image_extension=filename.substring(filename.indexOf(".")+1);
						
						in =fileItem.getInputStream();
						
					}else{
						String fielName=fileItem.getFieldName();
						String value=fileItem.getString("utf-8");
						params.put(fielName, value);
						
					}
				}
				String date=getDate();
				String filepath=savePath+params.get("jobNumber")+date+"."+image_extension;
				params.put(photoFieldName, filepath);
				out = new BufferedOutputStream(new FileOutputStream(new File(filepath)));
				Streams.copy(in, out, true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return params;
		
	}
	public String getDate(){
		Date date=new Date();
		int year=date.getYear()+1900;
		int month=date.getMonth()+1;
		int day=date.getDate();
		
		return year+""+month+""+day;
	}
}
